/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.machineryrental.weblayer.validator;

import cz.muni.fi.pa165.machineryrental.dto.RentalDTO;
import cz.muni.fi.pa165.machineryrental.service.RentalService;
import cz.muni.fi.pa165.machineryrental.weblayer.custommodels.CustomerMachineSearch;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author Marian Lorenc, 374122
 */
@Component
public class RentalValidator implements Validator {

    @Autowired
    private RentalService rentalService;

    @Override
    public boolean supports(Class<?> type) {
        return RentalDTO.class.equals(type) || CustomerMachineSearch.class.equals(type);
    }

    @Override
    public void validate(Object o, Errors errors) {

        if (o instanceof CustomerMachineSearch) {
            return;
        }

        ValidationUtils.rejectIfEmpty(errors, "dateOfRent", "rental.dateOfRent.empty");

        RentalDTO rental = (RentalDTO) o;

        if (rental.getCustomer() == null) {
            errors.rejectValue("customer", "rental.customer.empty");
        }

        if (rental.getMachine() == null) {
            errors.rejectValue("machine", "rental.machine.empty");
        }

        if (rental.getDateOfReturn() != null && rental.getDateOfRent() != null) {
            if (rental.getDateOfReturn().getTime() < rental.getDateOfRent().getTime()) {
                errors.rejectValue("dateOfReturn", "rental.duration.negative");
            }
        }

    }

}
